import { useState, useEffect } from 'react';
import { autorun } from 'mobx';

import { cityStore } from '../mobx/store';

const useCity = () => {
  const [cityId, setCityId] = useState('');
  const [cityName, setCityName] = useState('');

  useEffect(() => {
    // 订阅
    let unsubscribe = autorun(() => {
      let { id, name } = cityStore;
      setCityId(id);
      setCityName(name);
    });
    return () => {
      // 取消订阅
      unsubscribe();
    };
  }, []);

  return { cityId, cityName };
};

const useCityList = () => {
  const [list, setList] = useState([]);

  useEffect(() => {
    if (cityStore.list.length === 0) {
      cityStore.fetchList();
    } else {
      console.log('useCity 缓存');
    }
    return () => {};
  }, []);

  useEffect(() => {
    // 订阅
    let unsubscribe = autorun(() => {
      setList(cityStore.list);
    });
    return () => {
      // 取消订阅
      unsubscribe();
    };
  }, []);
  return {
    list,
  };
};

export { useCity, useCityList };
